from fastapi import APIRouter, Depends
from typing import Dict, List, Any
import os
import psutil
import platform
from datetime import datetime
from .auth import get_current_active_user, User

router = APIRouter(
    prefix="/api/stats",
    tags=["系统统计"],
    responses={404: {"description": "Not found"}},
)

@router.get("/system")
async def get_system_stats(current_user: User = Depends(get_current_active_user)):
    """获取系统状态信息"""
    cpu_usage = psutil.cpu_percent(interval=0.5)
    memory = psutil.virtual_memory()
    disk = psutil.disk_usage('/')
    
    return {
        "cpu": {
            "usage": cpu_usage,
            "cores": psutil.cpu_count(logical=True)
        },
        "memory": {
            "total": memory.total,
            "available": memory.available,
            "used": memory.used,
            "percent": memory.percent
        },
        "disk": {
            "total": disk.total,
            "free": disk.free,
            "used": disk.used,
            "percent": disk.percent
        },
        "system": {
            "platform": platform.system(),
            "release": platform.release(),
            "version": platform.version(),
            "processor": platform.processor(),
            "boot_time": datetime.fromtimestamp(psutil.boot_time()).isoformat()
        },
        "timestamp": datetime.now().isoformat()
    }

@router.get("/processes")
async def get_process_stats(current_user: User = Depends(get_current_active_user)):
    """获取流程执行统计信息"""
    # 这里是示例数据，实际应该从数据库获取
    return {
        "total": 10,
        "running": 2,
        "completed": 7,
        "failed": 1,
        "execution_stats": {
            "last_7_days": [5, 3, 8, 4, 2, 7, 6],
            "success_rate": 85.5,
            "avg_duration": 120
        },
        "top_processes": [
            {"name": "财务数据处理", "executions": 25, "success_rate": 96},
            {"name": "客户数据导入", "executions": 18, "success_rate": 89},
            {"name": "周报生成", "executions": 12, "success_rate": 100}
        ]
    }

@router.get("/ai")
async def get_ai_stats(current_user: User = Depends(get_current_active_user)):
    """获取AI使用统计信息"""
    # 这里是示例数据，实际应该从数据库获取
    return {
        "total_calls": 156,
        "tokens_used": 28547,
        "model_usage": {
            "glm-4": 120,
            "glm-3-turbo": 36
        },
        "cost_estimate": 12.85,
        "usage_by_feature": {
            "text_analysis": 68,
            "code_generation": 45,
            "image_recognition": 23,
            "other": 20
        }
    } 